package com.trumeen.immichgallery.ui.screen

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import coil.request.CachePolicy
import com.trumeen.immichgallery.MainApplication
import com.trumeen.immichgallery.repository.AuthManager
import com.trumeen.immichgallery.ui.navigation.Screen
import com.trumeen.immichgallery.viewmodel.ConnectionStatus
import com.trumeen.immichgallery.viewmodel.MainViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject

@Composable
fun FullscreenImageScreen(
    navController: NavController,
    viewModel: MainViewModel = hiltViewModel()
) {
    val assets by viewModel.assets.collectAsState()
    val currentIndex by viewModel.currentIndex.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val errorMessage by viewModel.errorMessage.collectAsState()
    val connectionStatus by viewModel.connectionStatus.collectAsState()
    val isPlaying by viewModel.isPlaying.collectAsState()

    val currentAsset = remember(currentIndex, assets) {
        derivedStateOf { assets.getOrNull(currentIndex) }
    }.value

    var showControls by remember { mutableStateOf(false) }
    val context = LocalContext.current

    // 检查连接状态，如果未连接则跳转到设置页面
    LaunchedEffect(connectionStatus) {
        if (connectionStatus != ConnectionStatus.CONNECTED) {
            navController.navigate(Screen.Settings)
        }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        // 全屏图片显示
        currentAsset?.let { asset ->
            // 使用带认证的图片加载器
            val imagePainter = rememberAsyncImagePainter(
                model = ImageRequest.Builder(context)
                    .data(asset.originalUrl)
                    .apply {
                        // 添加认证头
                        val authManager = (context.applicationContext as MainApplication)
                            .authManager
                        val token = kotlin.runCatching {
                            kotlinx.coroutines.runBlocking {
                                authManager.getAccessToken()
                            }
                        }.getOrNull()

                        if (!token.isNullOrBlank()) {
                            addHeader("Authorization", "Bearer $token")
                        }
                    }
                    .diskCachePolicy(CachePolicy.ENABLED)
                    .memoryCachePolicy(CachePolicy.ENABLED)
                    .crossfade(true)
                    .listener(
                        onError = { request, throwable ->
                            Log.e("FullscreenImage", "Image loading error: ${throwable.throwable.message}", throwable.throwable)
                            // 如果加载失败，尝试使用缩略图
                            if (request.data.toString().contains("/original")) {
                                Log.d("FullscreenImage", "Retrying with thumbnail")
                                // 这里可以添加重试逻辑，使用缩略图URL
                            }
                        },
                        onSuccess = { request, metadata ->
                            Log.d("FullscreenImage", "Image loaded successfully: ${request.data}")
                        }
                    )
                    .build()
            )

            Image(
                painter = imagePainter,
                contentDescription = "全屏照片",
                modifier = Modifier
                    .fillMaxSize()
                    .pointerInput(Unit) {
                        detectTapGestures {
                            showControls = !showControls
                        }
                    }
                    .pointerInput(Unit) {
                        detectHorizontalDragGestures { _, dragAmount ->
                            when {
                                dragAmount < -50 -> viewModel.nextAsset()
                                dragAmount > 50 -> viewModel.previousAsset()
                            }
                        }
                    },
                contentScale = ContentScale.Crop
            )
        }

        // 加载指示器
        if (isLoading) {
            CircularProgressIndicator(
                modifier = Modifier.align(Alignment.Center),
                color = MaterialTheme.colorScheme.primary
            )
        }

        // 错误提示
        errorMessage?.let {
            Text(
                text = it,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier
                    .align(Alignment.Center)
                    .padding(16.dp)
            )
        }

        // 控制按钮
        if (showControls) {
            // 设置按钮
            IconButton(
                onClick = { navController.navigate(Screen.Settings) },
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(16.dp)
                    .size(48.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Settings,
                    contentDescription = "设置",
                    tint = MaterialTheme.colorScheme.onBackground,
                    modifier = Modifier.size(32.dp)
                )
            }

            // 幻灯片控制按钮
            IconButton(
                onClick = {
                    if (isPlaying) viewModel.stopSlideshow() else viewModel.startSlideshow()
                },
                modifier = Modifier
                    .align(Alignment.TopStart)
                    .padding(16.dp)
                    .size(48.dp)
            ) {
                Icon(
                    imageVector = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow,
                    contentDescription = if (isPlaying) "暂停" else "播放",
                    tint = MaterialTheme.colorScheme.onBackground,
                    modifier = Modifier.size(32.dp)
                )
            }

            // 服务器状态指示器
            Box(
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .padding(top = 16.dp)
            ) {
                com.trumeen.immichgallery.ui.components.ServerStatusIndicator(
                    status = connectionStatus
                )
            }
        }
    }
}